// src/screens/RechargeScreen.js
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, TextInput, Alert, ScrollView } from 'react-native';
import { useSelector } from 'react-redux';
import api from '../services/api';

const RechargeScreen = ({ navigation }) => {
  const userInfo = useSelector(state => state.user.userInfo);
  const [selectedPackage, setSelectedPackage] = useState(null);
  const [customAmount, setCustomAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [paymentMethods, setPaymentMethods] = useState([]);

  useEffect(() => {
    fetchPaymentMethods();
  }, []);

  // 检测用户所在国家
  const detectUserCountry = async () => {
    try {
      // 首先尝试从用户信息中获取国家
      if (userInfo && userInfo.country) {
        return userInfo.country;
      }
      
      // 如果用户信息中没有国家，则通过IP地理位置检测
      const response = await fetch('https://ipapi.co/json/');
      const data = await response.json();
      return data.country_code || 'CN';
    } catch (error) {
      // 如果检测失败，默认为中国
      console.log('检测用户国家失败，使用默认国家CN', error);
      return 'CN';
    }
  };

  const fetchPaymentMethods = async () => {
    try {
      setLoading(true);
      const response = await api.getPaymentMethods();
      console.log('获取支付方式响应:', response);
      if (response.success) {
        // 检测用户所在国家
        const userCountry = await detectUserCountry();
        console.log('用户国家:', userCountry);
        
        // 确保 data 是对象（地区映射）
        if (typeof response.data === 'object' && response.data !== null) {
          // 获取用户所在国家的支付方式
          const countryMethods = response.data[userCountry] || response.data['CN'] || [];
          setPaymentMethods(countryMethods);
        } else {
          setPaymentMethods([]);
        }
      } else {
        // 如果获取失败，使用默认支付方式（Stripe + PayPal）
        setPaymentMethods([
          { 
            id: 'stripe-card',
            name: '信用卡支付', 
            description: '通过Stripe使用信用卡支付',
            icon: 'stripe-icon'
          },
          { 
            id: 'paypal', 
            name: 'PayPal', 
            description: '使用PayPal进行充值',
            icon: 'paypal-icon'
          }
        ]);
      }
    } catch (error) {
      console.log('获取支付方式失败:', error);
      // 如果获取失败，使用默认支付方式（Stripe + PayPal）
      setPaymentMethods([
        { 
          id: 'stripe-card', 
          name: '信用卡支付', 
          description: '通过Stripe使用信用卡支付',
          icon: 'stripe-icon'
        },
        { 
          id: 'paypal', 
          name: 'PayPal', 
          description: '使用PayPal进行充值',
          icon: 'paypal-icon'
        }
      ]);
    } finally {
      setLoading(false);
    }
  };

  const rechargePackages = [
    { id: 1, diamonds: 100, price: 10, bonus: 0 },
    { id: 2, diamonds: 500, price: 50, bonus: 50 },
    { id: 3, diamonds: 1000, price: 100, bonus: 150 },
    { id: 4, diamonds: 5000, price: 500, bonus: 1000 }
  ];

  const handlePaymentMethodSelect = async (method) => {
    // 根据选择的支付方式进行相应的处理
    switch (method.id) {
      case 'paypal':
        await handlePaypalRecharge();
        break;
      case 'wechat-pay':
        navigation.navigate('WeChatPay');
        break;
      case 'alipay':
        await handleAlipay();
        break;
      case 'apple-pay':
        await handleApplePay();
        break;
      case 'yoomoney':
        await handleYooMoney();
        break;
      case 'mir':
        await handleMirPay();
        break;
      case 'stripe-card':
        await handleStripeCard();
        break;
      default:
        await handleDirectRecharge();
    }
  };

  const handleDirectRecharge = async () => {
    let amount, diamonds;
    
    if (selectedPackage) {
      amount = selectedPackage.price;
      diamonds = selectedPackage.diamonds + selectedPackage.bonus;
    } else if (customAmount && !isNaN(customAmount) && parseFloat(customAmount) > 0) {
      amount = parseFloat(customAmount);
      diamonds = Math.floor(amount * 10); // 1元=10粉钻
    } else {
      Alert.alert('提示', '请选择充值套餐或输入有效金额');
      return;
    }

    setLoading(true);
    try {
      // 这里应该调用实际的支付接口
      const response = await api.rechargeDiamonds(amount, diamonds);
      if (response.success) {
        Alert.alert('成功', `充值成功，获得 ${diamonds} 粉钻！`);
        navigation.goBack();
      } else {
        Alert.alert('失败', response.message || '充值失败');
      }
    } catch (error) {
      Alert.alert('错误', '充值失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleWeChatPay = async () => {
    let amount, diamonds;
    
    if (selectedPackage) {
      amount = selectedPackage.price;
      diamonds = selectedPackage.diamonds + selectedPackage.bonus;
    } else if (customAmount && !isNaN(customAmount) && parseFloat(customAmount) > 0) {
      amount = parseFloat(customAmount);
      diamonds = Math.floor(amount * 10);
    } else {
      Alert.alert('提示', '请选择充值套餐或输入有效金额');
      return;
    }

    setLoading(true);
    try {
      // 调用后端处理微信支付
      const response = await api.processPayment({
        method: 'wechat-pay',
        amount: amount * 100, // 微信支付通常以分为单位
        description: `充值 ${diamonds} 粉钻`,
      });
      
      if (response.success) {
        Alert.alert('成功', `微信支付订单创建成功，请在微信中完成支付`);
        navigation.goBack();
      } else {
        Alert.alert('失败', response.message || '创建微信支付订单失败');
      }
    } catch (error) {
      Alert.alert('错误', '创建微信支付订单失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleAlipay = async () => {
    let amount, diamonds;
    
    if (selectedPackage) {
      amount = selectedPackage.price;
      diamonds = selectedPackage.diamonds + selectedPackage.bonus;
    } else if (customAmount && !isNaN(customAmount) && parseFloat(customAmount) > 0) {
      amount = parseFloat(customAmount);
      diamonds = Math.floor(amount * 10);
    } else {
      Alert.alert('提示', '请选择充值套餐或输入有效金额');
      return;
    }

    setLoading(true);
    try {
      // 调用后端处理支付宝支付
      const response = await api.processPayment({
        method: 'alipay',
        amount: amount,
        description: `充值 ${diamonds} 粉钻`,
      });
      
      if (response.success) {
        Alert.alert('成功', `支付宝订单创建成功，请在支付宝中完成支付`);
        navigation.goBack();
      } else {
        Alert.alert('失败', response.message || '创建支付宝订单失败');
      }
    } catch (error) {
      Alert.alert('错误', '创建支付宝订单失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleApplePay = async () => {
    let amount, diamonds;
    
    if (selectedPackage) {
      amount = selectedPackage.price;
      diamonds = selectedPackage.diamonds + selectedPackage.bonus;
    } else if (customAmount && !isNaN(customAmount) && parseFloat(customAmount) > 0) {
      amount = parseFloat(customAmount);
      diamonds = Math.floor(amount * 10);
    } else {
      Alert.alert('提示', '请选择充值套餐或输入有效金额');
      return;
    }

    setLoading(true);
    try {
      // 调用后端处理Apple Pay支付
      const response = await api.processPayment({
        method: 'apple-pay',
        amount: amount,
        description: `充值 ${diamonds} 粉钻`,
        paymentData: {}, // 实际应用中需要传递Apple Pay支付数据
      });
      
      if (response.success) {
        Alert.alert('成功', `Apple Pay支付处理成功`);
        navigation.goBack();
      } else {
        Alert.alert('失败', response.message || 'Apple Pay支付处理失败');
      }
    } catch (error) {
      Alert.alert('错误', 'Apple Pay支付处理失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleYooMoney = async () => {
    let amount, diamonds;
    
    if (selectedPackage) {
      amount = selectedPackage.price;
      diamonds = selectedPackage.diamonds + selectedPackage.bonus;
    } else if (customAmount && !isNaN(customAmount) && parseFloat(customAmount) > 0) {
      amount = parseFloat(customAmount);
      diamonds = Math.floor(amount * 10);
    } else {
      Alert.alert('提示', '请选择充值套餐或输入有效金额');
      return;
    }

    setLoading(true);
    try {
      // 调用后端处理YooMoney支付
      const response = await api.processPayment({
        method: 'yoomoney',
        amount: amount,
        description: `充值 ${diamonds} 粉钻`,
      });
      
      if (response.success) {
        Alert.alert('成功', `YooMoney支付订单创建成功，请在YooMoney中完成支付`);
        navigation.goBack();
      } else {
        Alert.alert('失败', response.message || '创建YooMoney支付订单失败');
      }
    } catch (error) {
      Alert.alert('错误', '创建YooMoney支付订单失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleMirPay = async () => {
    let amount, diamonds;
    
    if (selectedPackage) {
      amount = selectedPackage.price;
      diamonds = selectedPackage.diamonds + selectedPackage.bonus;
    } else if (customAmount && !isNaN(customAmount) && parseFloat(customAmount) > 0) {
      amount = parseFloat(customAmount);
      diamonds = Math.floor(amount * 10);
    } else {
      Alert.alert('提示', '请选择充值套餐或输入有效金额');
      return;
    }

    setLoading(true);
    try {
      // 调用后端处理MIR支付
      const response = await api.processPayment({
        method: 'mir',
        amount: amount,
        description: `充值 ${diamonds} 粉钻`,
      });
      
      if (response.success) {
        Alert.alert('成功', `MIR支付订单创建成功，请在MIR中完成支付`);
        navigation.goBack();
      } else {
        Alert.alert('失败', response.message || '创建MIR支付订单失败');
      }
    } catch (error) {
      Alert.alert('错误', '创建MIR支付订单失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleStripeCard = async () => {
    let amount, diamonds;
    
    if (selectedPackage) {
      amount = selectedPackage.price;
      diamonds = selectedPackage.diamonds + selectedPackage.bonus;
    } else if (customAmount && !isNaN(customAmount) && parseFloat(customAmount) > 0) {
      amount = parseFloat(customAmount);
      diamonds = Math.floor(amount * 10);
    } else {
      Alert.alert('提示', '请选择充值套餐或输入有效金额');
      return;
    }

    setLoading(true);
    try {
      // Stripe支付将在前端直接处理
      const response = await api.processPayment({
        method: 'stripe-card',
        amount: amount,
        description: `充值 ${diamonds} 粉钻`,
      });
      
      if (response.success) {
        Alert.alert('成功', `Stripe支付处理成功`);
        navigation.goBack();
      } else {
        Alert.alert('失败', response.message || 'Stripe支付处理失败');
      }
    } catch (error) {
      Alert.alert('错误', 'Stripe支付处理失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handlePaypalRecharge = async () => {
    let amount, diamonds;
    
    if (selectedPackage) {
      amount = selectedPackage.price;
      diamonds = selectedPackage.diamonds + selectedPackage.bonus;
    } else if (customAmount && !isNaN(customAmount) && parseFloat(customAmount) > 0) {
      amount = parseFloat(customAmount);
      diamonds = Math.floor(amount * 10); // 1元=10粉钻
    } else {
      Alert.alert('提示', '请选择充值套餐或输入有效金额');
      return;
    }

    setLoading(true);
    try {
      // 创建 PayPal 订单
      const response = await api.createPaypalOrder(amount, diamonds);
      if (response.success) {
        const orderId = response.data.orderId;
        // 跳转到 PayPal 支付页面
        navigation.navigate('Paypal', { orderId });
      } else {
        Alert.alert('失败', response.message || '创建支付订单失败');
      }
    } catch (error) {
      Alert.alert('错误', '创建支付订单失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>粉钻充值</Text>
        <Text style={styles.subtitle}>充值粉钻，畅享VIP特权</Text>
      </View>

      <View style={styles.userInfo}>
        <Text style={styles.diamondsText}>
          当前粉钻余额: {userInfo.diamonds || 0}
        </Text>
      </View>

      <Text style={styles.sectionTitle}>充值套餐</Text>
      <View style={styles.packagesContainer}>
        {rechargePackages.map((pkg) => (
          <TouchableOpacity
            key={pkg.id}
            style={[
              styles.packageCard,
              selectedPackage && selectedPackage.id === pkg.id && styles.selectedPackage
            ]}
            onPress={() => setSelectedPackage(pkg)}
          >
            <Text style={styles.diamondsAmount}>{pkg.diamonds} 粉钻</Text>
            {pkg.bonus > 0 && (
              <Text style={styles.bonusText}>赠送 {pkg.bonus} 粉钻</Text>
            )}
            <Text style={styles.packagePrice}>¥ {pkg.price}</Text>
          </TouchableOpacity>
        ))}
      </View>

      <View style={styles.customRechargeContainer}>
        <Text style={styles.sectionTitle}>自定义金额</Text>
        <TextInput
          style={styles.amountInput}
          placeholder="输入充值金额（元）"
          keyboardType="numeric"
          value={customAmount}
          onChangeText={setCustomAmount}
        />
        {customAmount !== '' && (
          <Text style={styles.estimatedDiamonds}>
            预计获得 {Math.floor(parseFloat(customAmount || 0) * 10)} 粉钻
          </Text>
        )}
      </View>

      <Text style={styles.sectionTitle}>支付方式</Text>
      <View style={styles.buttonContainer}>
        {loading ? (
          <Text>加载支付方式中...</Text>
        ) : Array.isArray(paymentMethods) && paymentMethods.length > 0 ? (
          paymentMethods.map((method) => (
            <TouchableOpacity
              key={method.id}
              style={[styles.rechargeButton, styles.paymentMethodButton]}
              onPress={() => handlePaymentMethodSelect(method)}
              disabled={loading}
            >
              <Text style={styles.rechargeButtonText}>
                {loading ? '处理中...' : method.name}
              </Text>
              <Text style={styles.paymentMethodDescription}>
                {method.description}
              </Text>
            </TouchableOpacity>
          ))
        ) : (
          <Text>暂无可用支付方式</Text>
        )}
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    backgroundColor: '#fff',
    padding: 20,
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#000',
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
    marginTop: 4,
  },
  userInfo: {
    backgroundColor: '#fff',
    padding: 16,
    margin: 16,
    borderRadius: 8,
    alignItems: 'center',
  },
  diamondsText: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#ff6b6b',
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#000',
    paddingHorizontal: 16,
    marginBottom: 12,
  },
  packagesContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingHorizontal: 16,
    justifyContent: 'space-between',
  },
  packageCard: {
    width: '48%',
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    marginBottom: 12,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#e0e0e0',
  },
  selectedPackage: {
    borderColor: '#ff6b6b',
    borderWidth: 2,
  },
  diamondsAmount: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#000',
  },
  bonusText: {
    fontSize: 14,
    color: '#ff6b6b',
    marginTop: 4,
  },
  packagePrice: {
    fontSize: 16,
    color: '#666',
    marginTop: 8,
  },
  customRechargeContainer: {
    backgroundColor: '#fff',
    marginHorizontal: 16,
    marginBottom: 16,
    borderRadius: 8,
    padding: 16,
  },
  amountInput: {
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
  },
  estimatedDiamonds: {
    fontSize: 14,
    color: '#666',
    marginTop: 8,
    textAlign: 'center',
  },
  buttonContainer: {
    margin: 16,
  },
  rechargeButton: {
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
    marginBottom: 12,
  },
  paymentMethodButton: {
    backgroundColor: '#2196F3',
  },
  rechargeButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
  },
  paymentMethodDescription: {
    fontSize: 12,
    color: '#fff',
    opacity: 0.9,
    marginTop: 4,
  },
});

export default RechargeScreen;